﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using NETMF.OpenSource.XBee.Api;
using NETMF.OpenSource.XBee.Api.Zigbee;

namespace WpfApplication1
{
    public class IoSampleListener : IPacketListener
    {
        public IoSampleListener()
        {
        }

        private ObservableCollection<string> logData;

        public IoSampleListener(ObservableCollection<string> log)
        {
            logData = log;
        }

        public bool Finished { get { return false; } }

        public void ProcessPacket(XBeeResponse packet)
        {
            if (packet is IoSampleResponse)
                ProcessIoSample(packet as IoSampleResponse);
        }

        private async void ProcessIoSample(IoSampleResponse packet)
        {
            double temp = packet.Analog[2];
            double mVanalog = (temp/1023.0)*1200;
            double temp_C = (mVanalog - 500.0)/10.0;
            double temp_f = temp_C*9/5 + 32;


            logData.Insert(0, string.Format("packet received from {0}: {1} - temp in c {2}; f {3}", packet.SourceAddress, DateTime.Now.ToLongTimeString(), temp_C, temp_f));
            string sURL;
            sURL = "http://tl-xbee.azurewebsites.net/home/set?temp=" + temp_f;


            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(sURL);


            //WebRequest wrGETURL;
            //wrGETURL = WebRequest.Create(sURL);
            //wrGETURL.GetResponse();
        }

        public XBeeResponse[] GetPackets(int timeout)
        {
            throw new System.NotSupportedException();
        }
    }
}
